<?php
namespace app\admin\controller;

use app\common\lib\Royal;

class Upload extends Common
{
    /**
     * 后台上传方法
     * @author 贺强
     * @time   2022/9/13 9:20
     */
    public function index()
    {
        if (!$this->request->isPost()) {
            $this->error('非法操作');
        }
        $files = $_FILES['Filedata'];
        if (empty($files)) {
            return ajax('要上传的文件不能为空', 101);
        }
        $debug = $_COOKIE['debug'] ?? ($_POST['debug'] ?? '');
        $type = $this->request->post('fileType', '');
        $flag = 1;
        $folder = $this->request->post('folder', '');
        $path = '';
        $msg = '上传成功';
        if (is_array($files['name'])) {
            for ($i = 0; $i < count($files['name']); $i++) {
                $file = ['name' => $files['name'][$i], 'type' => $files['type'][$i], 'tmp_name' => $files['tmp_name'][$i], 'error' => $files['error'][$i], 'size' => $files['size'][$i]];
                $res = Royal::upload($file, $folder, $type);
                if ($debug === 'upload' || $debug === 'upload' . $i) {
                    var_dump($res);
                    exit;
                }
                if (!empty($res['code']) && $res['code'] === 200) {
                    $path .= ',' . $res['path'];
                } else {
                    $flag++;
                    $msg = $res['message'];
                }
            }
            if (!empty($path)) {
                $path = substr($path, 1);
            }
        } else {
            $res = Royal::upload($files, $folder, $type);
            if ($debug === 'upload') {
                var_dump($res);
                exit;
            }
            if (!empty($res['code']) && $res['code'] === 200) {
                $path = $res['path'];
            } else {
                $flag = 0;
                $msg = $res['message'] ?? '上传失败';
            }
        }
        $path = str_replace('\\', '/', $path);
        if ($flag === 1) {
            return ajax($msg, 200, $path);
        } elseif ($flag > 1) {
            return ajax($msg, 201);
        } else {
            return ajax($msg, 401);
        }
    }

    public function upload()
    {
        return view();
    }
}
